using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Enter.Admin.Entities;
using Enter.Admin.Enums;
using Enter.Admin.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Enter.Admin.Tasks
{
    public class TimedHostedService : IHostedService, IDisposable
    {
        // services.AddHostedService<TimedHostedService>();
        
        private readonly ILogger<TimedHostedService> _logger;
        private readonly IFreeSql _fsql;
        private readonly IConfiguration _configuration;
        private readonly NoticeJob _noticeJob;
        private Timer _timer;

        public TimedHostedService(ILogger<TimedHostedService> logger, IFreeSql fsql, IConfiguration configuration)
        {
            _logger = logger;
            _fsql = fsql;
            _configuration = configuration;
            _noticeJob = new NoticeJob(_logger, _fsql, _configuration);
        }

        public Task StartAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("定时任务服务运行中.");

            _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromHours(12));

            return Task.CompletedTask;
        }

        private void DoWork(object state)
        {
            _noticeJob.Execute();
        }

        public Task StopAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("定时任务服务停止中.");

            _timer?.Change(Timeout.Infinite, 0);

            return Task.CompletedTask;
        }

        public void Dispose()
        {
            _timer?.Dispose();
        }
    }
}